var express = require('express');
// const { resolve } = require('path');
var router = express.Router();
var db = require('../sql')

// 1.新增/修改购物车数量
router.post('/add', async function (req, res) {
    // 跨域
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    let { shopid, _id: foodid, label, num, userid } = req.body
    // 序列化商品标签
    label = JSON.stringify(Object.values(label).reduce((arr, item) => {
        return arr.concat(item);
    }, []));

    // 查询数据库是否有该标签+商品id+商店id+用户id完全相同的数
    const checkShopCar = new Promise((resolve, reject) => {
        db.query('select * from shopcar where shopid=? and foodid=? and label=? and userid=?', [shopid, foodid, label, userid], function (err, data) {
            if (err) {
                reject(err);
            } else {
                if (data.length) {
                    resolve({ code: 200, data: data[0] })
                } else {
                    resolve({ code: 404 });
                }
            }
        })
    })
    const checkInfo = await checkShopCar;
    if (checkInfo.code == 404) {
        db.query(`insert into shopcar (shopid,foodid,label,num,userid) 
        values (?,?,?,?,?)`,
            [shopid, foodid, label, num, userid],
            function (err, data) {
                if (err) {
                    throw err
                } else {
                    res.send(data);
                }
            })
    } else if (checkInfo.code == 200) {
        const { id, num: dbNum } = checkInfo.data;
        const upDataShopCar = new Promise((resolve, reject) => {
            db.query('UPDATE shopcar SET num=? where id=?', [num + dbNum, id],
                function (err, data) {
                    if (err) {
                        throw err
                    } else {
                        res.send({ code: 200, data })
                    }
                })
        })
        await upDataShopCar
    }


})

// 2.获取购物车动态数据
router.get('/get', async function (req, res) {
    // 跨域
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    let { shopid, userid } = req.query
    const checkShopCar = new Promise((resolve, reject) => {
        db.query('select * from shopcar where shopid=? and userid=?', [shopid, userid],
            function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    if (data.length) {
                        resolve({ code: 200, data })
                    } else {
                        resolve({ code: 404 });
                    }
                }
            })
    })
    const shopcardata = await checkShopCar
    const carData = shopcardata.data || []
    if (shopcardata.code == 200) {
        for (let i in carData) {
            const FoodInfo = new Promise((resolve, reject) => {
                db.query('select * from foodlist where _id=?', [carData[i].foodid],
                    function (err, data) {
                        if (err) {
                            reject(err);
                        } else {
                            if (data.length) {
                                resolve({ code: 200, data })
                            } else {
                                resolve({ code: 404 });
                            }
                        }
                    })
            })
            const FoodInfoData = await FoodInfo
            console.log("-------------")
            console.log("数据",FoodInfoData.data);
            console.log("-------------")
            // if(FoodInfo.data){
                FoodInfoData.data[0].label = JSON.parse(FoodInfoData.data[0].label)
            carData[i].label = JSON.parse(carData[i].label)
            carData[i] = {
                ...FoodInfoData.data[0],
                ...carData[i]
            }
            // }
        }
    }
    setTimeout(() => {
        const totalMoney = carData.reduce((sum, item) => {
            return sum + item.num * item.price
        }, 0);
        const total = carData.reduce((sum, item) => {
            return sum + item.num
        }, 0);
        res.send({
            totalMoney,
            total,
            shops: carData
        })
    }, 500)
})

// 改变购物车数量
// 3.新增/修改购物车数量
router.get('/change', async function (req, res) {
    let { id, num, state } = req.query
    if (state == false || state == 'false') {
        num--
    } else {
        num++;
    }
    if (num >= 1) {
        db.query('UPDATE shopcar SET num=? where id=?', [num, id],
            function (err, data) {
                if (err) {
                    throw err
                } else {
                    res.send({ code: 200, data })
                }
            })
    } else {
        db.query('delete from shopcar where id=?', [id],
            function (err, data) {
                if (err) {
                    throw err
                } else {
                    res.send({ code: 200, data })
                }
            })
    }
}

)

// 4.清空用户+商店指定的购物车
router.get('/clear', async function (req, res) {
    let { shopid, userid } = req.query
    db.query('delete from shopcar where shopid=? and userid=?', [shopid, userid],
        function (err, data) {
            if (err) {
                throw err
            } else {
                res.send({ code: 200, data })
            }
        })
})

// 5.获取用户的购物车列表
router.get('/userShopCar', async function (req, res) {
    let { userid } = req.query;
    // 1.获取用户所有购物车中的商店数据
    const userCarArr = new Promise((resolve, reject) => {
        db.query('select * from shopcar where userid=?', [userid],
            function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve({ code: 200, data })
                }
            })
    })
    const userShopCarInfo = await userCarArr;
    const finalUserShopCarInfo = []
    if (userShopCarInfo.code == 200) {
        // 1.1、去除商店id数据，组成商店id数组
        const DuplicateItemArray = userShopCarInfo.data.map(n => n.shopid);
        const shopIdArr = Array.from(new Set(DuplicateItemArray));
        for (let item of shopIdArr) {
            // 2.根据id获取商店的信息
            // 3.合并成商店的完整信息
            const ShopInfo = new Promise((resolve, reject) => {
                db.query('select * from shop where id=?', [item],
                    function (err, data) {
                        if (err) {
                            reject(err);
                        } else {
                            resolve({ code: 200, data })
                        }
                    })
            })
            const resShopInfo = await ShopInfo
            if(resShopInfo.code==200){
                // 查询购物车里面
                const {id} = resShopInfo.data[0]
                const ShopCARINFO = new Promise((resolve, reject) => {
                    db.query('select * from shopcar where shopid=?', [id],
                        function (err, data) {
                            if (err) {
                                reject(err);
                            } else {
                                resolve({ code: 200, data })
                            }
                        })
                })
                const resShopCARINFO = await ShopCARINFO;
                if(resShopCARINFO.code==200){
                    for(let carItem in resShopCARINFO.data){
                        // console.log(carItem.foodid,'食物id');
                        const getFoodDetail = new Promise((resolve, reject) => {
                            db.query('select * from foodlist where _id=?', [resShopCARINFO.data[carItem].foodid],
                                function (err, data) {
                                    if (err) {
                                        reject(err);
                                    } else {
                                        resolve({ code: 200, data })
                                    }
                                })
                        })
                        const resFoodDetail = await getFoodDetail;
                        resShopCARINFO.data[carItem]= {
                            ...resFoodDetail.data[0],
                            ...resShopCARINFO.data[carItem]
                        }
                    }
                    resShopCARINFO.data = resShopCARINFO.data.map(n=>{
                        return {
                            ...n,
                            label:JSON.parse(n.label)
                        }
                    })
                    resShopInfo.data[0]['selectShopCar'] = resShopCARINFO.data;
                    // 总件数和总价格
                    resShopInfo.data[0]['sumPrice'] = resShopCARINFO.data.reduce((sum,n)=>{
                        return sum+n.price*n.num
                    },0)
                    resShopInfo.data[0]['sumCount'] = resShopCARINFO.data.reduce((sum,n)=>{
                        return sum+n.num
                    },0)
                }
                finalUserShopCarInfo.push(resShopInfo.data[0]);
            }
        }
    }
        res.send({code:200,data:finalUserShopCarInfo});
})
module.exports = router;
